<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.List" %>
<%@ page import="com.andy.sun.bean.Motto" %>
<%@ page import="com.andy.sun.services.MottoService" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>感悟·格言</title>
    <link href="css/bootstrap.css" rel="stylesheet">
    <script src="js/jquery-3.5.1.js"></script>
    <script src="js/bootstrap.js"></script>
    <link rel="icon" href="images/12.ico">
    <style>
        body {
            background-color: #eecdee;
        }

        #mottoTitle {
            text-align: center;
            font-size: 55px;
            color: blue;
            font-family: 华文行楷;
        }

        .thumbnail {
            position: relative;
             /*添加背景图片拉伸,不重复*/
            margin-top: 10%;
            background-repeat: no-repeat;
            background-position: center center;
            background-size: 100% 100%; /* 图片拉伸显示 */
        }

        .delMotto {
            position: absolute;
            top: 3px;
            right: 3px;
            font-size: 20px;
            cursor: pointer;
        }
        .delMotto span {
            color: #0000ff;
            width: 22px;
            height: 22px;
            padding: 2px;
        }

        .showMottoId {
            background-color: #a4a4f3;
        }

        #addTip {
            font-size: 33px;
            width: 100%;
            text-align: center;
            margin-top: 100px;
            font-family: 幼圆;
            margin-bottom: 50px;
            color: #ff0000;
        }

        #loading {
            fontsize: 44px;
            font-weight: bold;
            text-align: center;
            margin-top: 50px;
            margin-bottom: 50px;
            color: #3550f5;
            font-family: 微软雅黑;
        }

        #addMottoModal {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 80%;
            height: fit-content;
            background-color: #fff;
            border-radius: 10px;
            box-shadow: 10px 10px 20px #474747;
            display: none;
        }

        #addMottoModal .modal-header {
            background-color: #eded63;
            color: #121af1;
            font-family: 微软雅黑;
        }

        #addMottoModal .modal-body {
            padding: 20px;
        }

        #addMottoModal .modal-footer {
            padding: 10px;
            text-align: center;
        }

        #addMottoModal input[type="text"] {
            width: 100%;
            height: 40px;
            padding: 10px;
            margin-bottom: 20px;
            border: none;
            border-radius: 5px;
            font-size: 18px;
            font-family: 微软雅黑;
        }

        #addMottoModal button[type="submit"], #addMottoModal button[type="button"] {
            width: 100px;
            height: 40px;
            color: #fff;
            border: none;
            border-radius: 5px;
            font-size: 18px;
            font-family: 微软雅黑;
            cursor: pointer;
        }

        #LinkBar {
            position: fixed;
            left: 20px;
            top: 260px;
        }

        #LinkBar button {
            margin: 10px;
            border-radius: 10px;
        }
        .motto_show{ /*让这个p标签首行缩进*/
            text-indent: 2em;
            margin: 2em;
            padding-right: 33px;
            white-space: pre-wrap; /* 允许换行 */
            word-wrap: break-word; /* 允许长单词换行 */
        }

        @media screen and (max-width: 768px) {
            #addMottoModal {
                width: 80%;
            }

            #addMottoModal button[type="submit"] {
                margin-left: 20px;
            }

            #addMottoModal button[type="button"] {
                margin-right: 20px;
            }

            #LinkBar {
                position: fixed;
                left: 80%;
                top: 210px;
            }

            #LinkBar .btn {
                margin: 5px;
                width: 80%;
                padding: 5px 20px 5px 10px;
                height: 50%;
                font-size: 14px;
            }
        }

        /*当鼠标移动到thumbnail上时,产生炫酷动画效果,让当前的内容晃动放大一些.*/
        .thumbnail:hover {
            transform: scale(1.1);
            transition: all 0.3s ease-in-out;
            z-index: 2;
        }
        @media screen and (min-width: 769px) {
            #addMottoModal {
                width: 60%;
            }

            #addMottoModal button[type="submit"] {
                margin-left: 50px;
            }

            #addMottoModal button[type="button"] {
                margin-right: 50px;
            }

            #motto {
                font-size: 24px;
                line-height: 30px;
                white-space: pre-wrap;
                resize: none;
            }

            #LinkBar {
                position: fixed;
                left: 20px;
                top: 260px;
            }

            #LinkBar button {
                margin: 10px;
                border-radius: 10px;
            }
        }
        .tips_how,.thumbnail {
        /*    设置背景透明*/
            background-color: rgba(0,0,0, 0%);
            border: none;
            box-shadow: none;
        }
    </style>
</head>
<body>
<%
    int uid = session.getAttribute("uid") == null ? 0 : Integer.parseInt(session.getAttribute("uid").toString());
    if (uid == 0) {
        response.sendRedirect("login.jsp");
        return;
    } else {
        final List<Motto> mottoList = new ArrayList<>();
        mottoList.clear();
        if (mottoList.size() < 20) {
            MottoService mottoService = new MottoService(uid);
            mottoList.addAll(mottoService.queryMottos(0));
        }
        session.setAttribute("mottoList", mottoList);
    }
%>
<%-- 导航栏 --%>
<nav class="navbar navbar-inverse">
    <div class="container-fluid">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">切换导航</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="getTask.jsp" target="_parent">首页·计划管理</a>
        </div>

        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
                <li><a target="_parent" href="TaskLineServlet">任务成就</a></li>
                <li><a target="_parent" href="ProSpectServlet?what=query">布局·规划</a></li>
                <li><a target="_parent" href="URLServlet?what=query">重要网址</a></li>
                <li><a target="_parent" href="NoteServlet?what=query">重要记事</a></li>
                <li><a target="_parent" href="mottos.jsp">感悟·格言</a></li>
                <li><a target="_parent" href="bookNotes.jsp">读书笔记</a></li>

            </ul>
            <form class="navbar-form navbar-left" role="search">
                <div class="form-group">
                    <input type="text" class="form-control" placeholder="Search">
                </div>
                <button type="submit" class="btn btn-default">搜索</button>
            </form>
            <ul class="nav navbar-nav navbar-right">
                <li><a target="_parent" id="login_out">
                    <% String uname = (String) session.getAttribute("uname");
                        String welcomeMessage = "欢迎,登录";
                        if (uname != null && !uname.isEmpty()) {
                            welcomeMessage = "欢迎," + uname + "[退出登录]";
                        }
                        out.print(welcomeMessage);
                    %>
                </a></li>
                <li><a target="_parent" href="regist.jsp">注册</a></li>
                <li><a target="_parent" href="#">会员中心</a></li>
                <li><a target="_parent" href="Contact_us.jsp">联系我们</a></li>
            </ul>
        </div>
    </div>
</nav>
<%-- 所有内容 --%>
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <h1 id="mottoTitle">感悟·格言</h1>
            <hr>
            <div class="row" id="mottoContainer">
                <c:forEach var="note" items="${mottoList}">
                    <div class="col-md-4 tips_how">
                        <div class="thumbnail">
                            <div class="caption">
                                <h6><span class="label label-primary showMottoId">${note.id}</span></h6>
                                <p class="motto_show">${note.motto}</p>
                                <p class="delMotto" id="del${note.id}"><span onclick="delMotto(${note.id})"
                                                                             class="btn btn-warning" role="button">X</span></p>
                            </div>
                        </div>
                    </div>
                </c:forEach>
            </div>
            <div id="loading" style="display:none;">------ 更多数据加载中... ------</div>
            <div id="addTip" style="${(mottoList==null)?'display:block':'display:none'};">暂无更多格言数据,快去添加吧!
                <span class="glyphicon glyphicon-heart"></span></div>
        </div>
    </div>
</div>
<%--添加格言模块--%>
<div id="addMottoModal" class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <h4 style="text-align: center;" class="modal-title"> 添 加 格 言 </h4>
        </div>
        <div class="modal-body">
            <form id="addMottoForm" action="MottosServlet" method="post">
                <div class="form-group">
                    <label for="motto">格言内容</label>
                    <textarea id="motto" cols="30" maxlength="200" class="form-control" name="motto"
                              placeholder="请输入你的感悟" rows="10"></textarea>
                </div>
            </form>
            <div class="modal-footer">
                <button id="add_close" type="button" class="btn btn-info" data-dismiss="modal">关闭</button>
                <button id="add_submit" type="submit" class="btn btn-info">提交</button>
            </div>
        </div>
    </div>
</div>
<!-- 创建一个垂直按钮组，用于操作任务列表的展开和折叠 -->
<div id="LinkBar" class="btn-group-vertical btn-group-lg" role="group" aria-label="...">
    <!-- 用于展开所有任务列表的按钮 -->
    <button type="button" id="addMottoBtn" class="btn btn-info">添加格言</button>
    <hr>
    <button type="button" id="to_top" class="btn btn-warning">回到顶部</button>
    <button type="button" id="to_bottom" class="btn btn-primary">跳到底部</button>
</div>

</body>
<script>
    const images = [    // 定义便签背景图片数组
        "images/note_bg/note_bg.png",
        "images/note_bg/note_bg_green.png",
        "images/note_bg/note_bg_purl.png",
        "images/note_bg/not_bg_red.png",
        "images/note_bg/note_bg_green2.png",
        "images/note_bg/note_bg_sky.png",
        "images/note_bg/note_bg_yellow.png"
    ];


    $("#addMottoBtn").click(function () {
        $("#addMottoModal").show(); // 显示添加格言模块
    });

    $("#add_close").click(function () {
        $("#addMottoModal").hide(); // 隐藏添加格言模块
        $("#motto").val("");
    });
    $("#add_submit").click(function () {
        var motto = $("#motto").val()
        $.ajax({
            url: "MottosServlet",
            type: "post",
            data: {"motto": motto},
            datatype: "json",
            success: function (motto) {
                if (motto) {
                    $("html,body").animate({scrollTop: 0}, 500);
                    $("#mottoContainer").prepend(`
                    <div class="col-md-4 tips_how">
                        <div class="thumbnail">
                            <div class="caption">
                                <h6><span class="label label-primary showMottoId">new</span></h6>
                                <p class="motto_show">`+motto.motto+`</p>
                                <p class="delMotto" id="del`+motto.id+`"><span onclick="delMotto(`+motto.id+`)"
                                                                             class="btn btn-warning" role="button">X</span></p>
                            </div>
                        </div>
                    </div>`);
                    let randomIndex = Math.floor(Math.random() * images.length);
                    let selectedImage = images[randomIndex];
                    $("#del"+motto.id).parent().parent().css("background-image", "url(" + selectedImage + ")");
                } else {
                    alert("添加失败!");
                }
            },
            error: function () {
                console.log("提交失败");
            }
        });
        $("#addMottoModal").hide(); // 隐藏添加格言模块
        $("#motto").val("");
    }); // 提交添加格言

    function delMotto(id){
        let b = confirm("确定要删除吗?");
        if (!b) {
            return;
        }
        $.ajax({
            url: "MottosServlet",
            type: "post",
            data: {"mottoId": id},
            datatype: "text",
            success: function (data) {
                if (data === "del_success") {
                    $("#del"+id).parent().parent().remove();
                }
            },
            error: function () {
                console.log("删除失败");
            }
        });

    } // 删除格言


    let isLoading = false; // 标志变量，表示是否正在加载
    // 滚动加载更多
    $(document).ready(function () {
        let scrollTimeout;
        sessionStorage.setItem('mottoIndex', "20"); // 获取当前索引
        $(window).on('scroll', function () {

            const distanceFromBottom = $(document).height() - ($(window).scrollTop() + window.innerHeight);
            /** console.log("\n文档总高度:"+$(document).height()
             + "\n滚动条总高度:"+$(window).scrollTop()
             +"\n窗体高度:"+$(window).height()
             +"\n屏幕的可见高度:"+window.innerHeight
             +"\n屏幕在y轴上的偏移量:"+window.pageYOffset
             +"\n距离底部" + distanceFromBottom);
             */
            // 当滚动条的位置加上窗口的高度大于等于文档的高度时
            if (distanceFromBottom < 1 && !isLoading) {
                isLoading = true; // 设置标志为正在加载
                $("#loading").show(); // 显示加载提示
                setTimeout(function () {
                    // 延迟加载，模拟网络请求
                    loadMoreMottos(); // 调用加载更多函数
                }, 1500);
            }

        });
    });

    function loadMoreMottos() {
        $("#loading").hide(); // 隐藏加载提示
        var index = sessionStorage.getItem('mottoIndex') || 20; // 获取当前索引
        $.ajax({
            url: "MottosServlet",
            type: "post",
            data: {index: index},
            datatype: "json",
            success: function (data) {
                if (data.length == 0) {
                    $('#loading').hide(); // 隐藏加载提示
                    $('#addTip').show(); // 显示添加提示
                    return;
                }
                // 将返回的新格言添加到页面中
                var mottoContainer = $('#mottoContainer');
                data.forEach(function (motto) {
                    var mottoHtml = `
                        <div class="col-md-4">
                            <div class="thumbnail">
                                <div class="caption">
                                    <h6><span class="label label-primary showMottoId">` + motto.id + `</span></h6>
                                    <p class="motto_show">` + motto.motto + `</p>
                                    <p class="delMotto" id="del` + motto.id + `"><span onclick="delMotto(` + motto.id + `)" class="btn btn-warning" role="button">X</span></p>
                                </div>
                            </div>
                        </div>`;
                    mottoContainer.append(mottoHtml); // 将新的格言HTML添加到容器中
                    let randomIndex = Math.floor(Math.random() * images.length);
                    let selectedImage = images[randomIndex];
                    $("#del"+motto.id).parent().parent().css("background-image", "url(" + selectedImage + ")");
                });

                isLoading = false; // 重置标志
                index = parseInt(index) + 20; // 增加索引
                sessionStorage.setItem('mottoIndex', index); // 更新索引
            },
            error: function () {
                console.log("加载更多格言失败");
            }
        });
    }

    //返回顶部和底部的按钮点击事件.
    $("#to_top").click(function () {
        $("html,body").animate({scrollTop: 0}, 500);
    });

    $("#to_bottom").click(function () {
        $("html,body").animate({scrollTop: $(document).height()}, 500);
    });

    // 将选择的图片设置为背景
    $(".thumbnail").each(function () {
        let randomIndex = Math.floor(Math.random() * images.length);
        let selectedImage = images[randomIndex];
        $(this).css("background-image", "url(" + selectedImage + ")");
    });

    $("#login_out").click(function () {
        let b = confirm("确定退出当前账号的登录吗?");
        if (b) {
            //删除浏览器中的cookie信息
            document.cookie = "task_uid=;expires=" + new Date(0).toUTCString();
            document.cookie = "task_uname=;expires=" + new Date(0).toUTCString();
            location.href = "login.jsp";
        }
    });

</script>
</html>
